<?php //

require 'Slim/Slim.php';
require 'DB.php';
$app = new Slim();
$app->config('debug', true);


$app->get('/rest/getAllCafes', 'getAllCafes');
$app->get('/rest/getCafeById/:cafeId', 'getCafeById');
$app->get('/rest/getCafeMenusByCafeId/:cafeId', 'getCafeMenusByCafeId');
$app->put('/rest/addUserReview','addUserReview');
$app->get('/rest/getReviewsByCafeId/:cafeId','getReviewsByCafeId');
$app->put('/rest/updateReviewById/:id','updateReviewById');
$app->put('/rest/addFundToCurrentCardHolder','addFundToCurrentCardHolder');
$app->put('/rest/addCardHolderTrackerByCardHolderId/:cardHolderId','addCardHolderTrackerByCardHolderId');
$app->put('/rest/authenticate','authenticate');
$app->get('/rest/getVisulizationData','getVisulizationData');
$app->PUT('/rest/addCardHolderTracker','addCardHolderTracker');

$app->get('/rest/getCurrentCardHolder','getCurrentCardHolder');
$app->PUT('/rest/logout','logout');
$app->run();




function getAllCafes() {
    $sql = "select * FROM cafe ORDER BY name";
    try {
        $dbb = DB::getConnection();
        $stmt = $dbb->query($sql);
        $cafes = $stmt->fetchAll(PDO::FETCH_OBJ);
        echo '{"cafes": ' . json_encode($cafes) . '}';
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
}


function getCafeMenusByCafeId($cafeId) {
    $sql = "SELECT * FROM cafe_menu WHERE cafe=:cafeId";
	try {
		$db = DB::getConnection();
		$stmt = $db->prepare($sql);  
		$stmt->bindParam("cafeId", $cafeId);
		$stmt->execute();
		$cafemenus = $stmt->fetchAll(PDO::FETCH_OBJ);
		$db = null;

		$toreturn = array();
       
        $cafemenus = array_chunk($cafemenus, 3);
       
        echo '{"cafemenus": ' . json_encode($cafemenus) . '}';
		//echo json_encode($wine);
	} catch(PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}'; 
	}
 
}


function getCafeById($cafeId) {
       
    $sql = "select * from cafe where id=:id";
        try {
                $db = DB::getConnection();
                $stmt = $db->prepare($sql); 
               
                $stmt->bindParam("id", $cafeId);
                $stmt->execute();
                $cafe = $stmt->fetchObject(); 
                
                
                echo json_encode($cafe); 
                $db = null;


        } catch(PDOException $e) {
                echo '{"error":{"text":'. $e->getMessage() .'}}'; 
        }
    
    
    
    
}




function getReviewsByCafeId($cafeId) {
    
    $sql = "SELECT  c.name as card_holder_name,r.id as id , r.comment as comment, r.cafe as cafe, r.card_holder as card_holder, r.rating as rating, DATE_FORMAT(r.timestamp, '%m/%d/%Y') as timestamp FROM review r, card_holder c WHERE cafe=:cafeId and c.id=r.card_holder order by r.timestamp DESC";
    try {
            $db = DB::getConnection();
            $stmt = $db->prepare($sql);  
            $stmt->bindParam("cafeId", $cafeId);
          
            $stmt->execute();
            $reviews = $stmt->fetchAll(PDO::FETCH_OBJ);  
            $db = null;
            echo '{"reviews": ' . json_encode($reviews) . '}';
            //echo json_encode($review); 
    } catch(PDOException $e) {
            echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    
}

function addUserReview() {
        //error_log('addWine\n', 3, '/var/tmp/php.log');
	$request = Slim::getInstance()->request();
	$review = json_decode($request->getBody());
        
        $cardholdObject = getCurrentCardHolderObject();
        if($cardholdObject == null) {
            echo '{"authenticated": false}'; 
            return;
        } 
        
        $cardHolderId = $cardholdObject->id;
	
	
	$sql = "INSERT INTO review (comment, rating,cafe,card_holder,timestamp) VALUES (:comment, :rating,:cafe,:card_holder,now())";
	try {
		$db = DB::getConnection();
		$stmt = $db->prepare($sql);  
		$stmt->bindParam("comment", $review->comment);
		$stmt->bindParam("rating", $review->rating);
		
                $stmt->bindParam("cafe", $review->cafe);
                $stmt->bindParam("card_holder", $cardHolderId);
		
		 
		$stmt->execute();
		$review->id = $db->lastInsertId();
		$db = null;
              
		echo json_encode($review); 
	} catch(PDOException $e) {
		//error_log($e->getMessage(), 3, '/var/tmp/php.log');
		echo '{"error":{"text":'. $e->getMessage() .'}}'; 
	}
}

function updateReviewById($id) {
        $request = Slim::getInstance()->request();
	$body = $request->getBody();
	$review = json_decode($body);
	$sql = "UPDATE review SET comment=:comment, rating=:rating WHERE id=:id";
	try {
		$db = DB::getConnection();
		$stmt = $db->prepare($sql);  
		$stmt->bindParam("comment", $review->comment);
		$stmt->bindParam("rating", $review->rating);
		$stmt->bindParam("id", $id);
                $review->id = $id;
		$stmt->execute();
		$db = null;
		echo json_encode($review); 
	} catch(PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}'; 
	}
}


function addFundToCurrentCardHolder() {
    $cardholdObject = getCurrentCardHolderObject();
    if($cardholdObject == null) {
        echo '{"authenticated": false}'; 
        return;
    } 
      
    try {
            $db = DB::getConnection();
            $request = Slim::getInstance()->request();
            $cardHolder = $cardholdObject;
            $body = $request->getBody();
            $fund = json_decode($body);
            $newBudgetPerMonth = (float)($cardHolder->budget_per_month + $fund->add_fund);

           //UPDATE CARD HOLDER BUDGET PER MONTH
            $updateSql = "UPDATE card_holder set budget_per_month=:budgetPerMonth where id = :cardHolderId";
            $stmt = $db->prepare($updateSql);  
            
            
            $stmt->bindParam("budgetPerMonth", $newBudgetPerMonth);
            $stmt->bindParam("cardHolderId", $cardHolder->id);
           
            $stmt->execute();
            
            
            
            $cardHolder->add_fund = $fund->add_fund;
            $cardHolder->budget_per_month = $newBudgetPerMonth;
            
            echo json_encode($cardHolder);
            
            
            $db = null;
          //  echo json_encode($fund); 
    } catch(PDOException $e) {
            echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    
}



function addCardHolderTracker() {
    $cardholdObject = getCurrentCardHolderObject();
    if($cardholdObject == null) {
        echo '{"authenticated": false}'; 
        return;
    } 
   // error_log('addCardHolderTrackerByCardHoderById\n', 3, '/var/tmp/php.log');
    $request = Slim::getInstance()->request();
    $cardHolderTracker = json_decode($request->getBody());
    $cardHolderId = $cardholdObject->id;

    $sql = "INSERT INTO card_holder_tracker (card_holder, total_purchase_amount,total_calories,timestamp) VALUES (:cardHolder, :totalPurchaseAmount,:totalCalories,now())";
    try {
            $db = DB::getConnection();
            $stmt = $db->prepare($sql);  
            $stmt->bindParam("cardHolder", $cardHolderId);
            $stmt->bindParam("totalPurchaseAmount", $cardHolderTracker->total_purchase_amount);
            $stmt->bindParam("totalCalories", $cardHolderTracker->total_calories);
            $stmt->execute();
            $cardHolderTracker->id = $db->lastInsertId();
            
            echo json_encode($cardHolderTracker); 
            $db = null;
    } catch(PDOException $e) {
            error_log($e->getMessage(), 3, '/var/tmp/php.log');
            echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
    
    
    
}

function getVisulizationData() {
    
    $cardholdObject = getCurrentCardHolderObject();
    if($cardholdObject == null) {
        echo '{"authenticated": false}'; 
        return false;
    } 
    
    $cardHolderId = $cardholdObject->id;
    
    $sevenDaysAgo = date('Y-m-d',strtotime('-8 days'));
    
    $sql = "select DATE_FORMAT(timestamp, '%m-%d-%Y') as date_time, sum(total_purchase_amount) as total_purchase_amount from campus_smart_foods.card_holder_tracker 
          where card_holder = :cardHolder and timestamp >= :sevenDaysAgo and timestamp <= now()  group by DATE_FORMAT(timestamp, '%m-%d-%Y') ";
    $db = DB::getConnection();
    $stmt = $db->prepare($sql);  
    $stmt->bindParam("cardHolder", $cardHolderId);
    $stmt->bindParam("sevenDaysAgo", $sevenDaysAgo);
    $stmt->execute();
            
    $result = $stmt->fetchAll(PDO::FETCH_OBJ);
    $dailyBarChartDates = array();
    $dailyBarchartAmounts = array();
    
    
   foreach ($result as $row) {
      //print_r($row);
       array_push($dailyBarChartDates,$row->date_time);
       array_push($dailyBarchartAmounts,$row->total_purchase_amount);
      
   }
   
   
   
   
   
   $return = array();
   $return["daily_barchart_dates"] = $dailyBarChartDates;
   $return["daily_barchart_purchase_amounts"] = $dailyBarchartAmounts;
   
   
   
    $firstDayMonth = date('Y-m-01');
    $sql = "select ch.budget_per_month as budget_per_month, DATE_FORMAT(cht.timestamp, '%m-%Y') as date_time, sum(cht.total_purchase_amount) as total_purchase_amount from card_holder_tracker cht,card_holder ch 
          where cht.card_holder = :cardHolder and cht.timestamp >= :firstDayMonth and cht.timestamp <= now() and cht.card_holder = ch.id group by DATE_FORMAT(cht.timestamp, '%m-%Y') ";
    $db = DB::getConnection();
    $stmt = $db->prepare($sql);  
    $stmt->bindParam("cardHolder", $cardHolderId);
    $stmt->bindParam("firstDayMonth", $firstDayMonth);
    $stmt->execute();
            
    $result = $stmt->fetchAll(PDO::FETCH_OBJ);
    
     
     foreach ($result as $row) {
      $return["budget_per_month"] = (float)$row->budget_per_month;
      $return["monthly_spent_amount"] = $row->total_purchase_amount;
      $return["monthly_left_amount"] = (float)$row->budget_per_month - (float)$row->total_purchase_amount;
      
      
   }
   
    if($result == null) {
      $return["monthly_spent_amount"] = 0;
      $return["monthly_left_amount"] = (float)$cardholdObject->budget_per_month ;
   }
   echo json_encode($return); 
   //print_r($barchart_date);
    
}

function getCurrentCardHolder() {
    
    $cardholdObject = getCurrentCardHolderObject();
    if($cardholdObject == null) {
        echo '{"authenticated": false}'; 
    } else {
        $cardholdObject->authenticated = true;
        echo json_encode($cardholdObject); 
    }
    
}

function getCurrentCardHolderObject() {
     // this starts the session 
   
    if (isset($_SESSION['current_card_holder_id'])) {
        
    
        $currentCardHolderId = $_SESSION['current_card_holder_id'];
      
        $sql = "select * from card_holder where id=:id";
            try {
                    $db = DB::getConnection();
                    $stmt = $db->prepare($sql); 
                   
                    $stmt->bindParam("id", $currentCardHolderId);
                    $stmt->execute();
                    $cardHolderObject = $stmt->fetchObject(); 
                    $db = null;
                    return $cardHolderObject;




            } catch(PDOException $e) {
                    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
            }
    
    } 
    
    
}

function authenticate() {
       
        $request = Slim::getInstance()->request();
	$body = $request->getBody();
	$cardHolder = json_decode($body);
       // print_r($cardHolder);
	$sql = "Select * from card_holder where card_number=:card_number and pin_code=:pincode";
	try {
		$db = DB::getConnection();
		$stmt = $db->prepare($sql);  
		$stmt->bindParam("card_number", $cardHolder->card_number);
		$stmt->bindParam("pincode", $cardHolder->pin_code);
		$stmt->execute();
                $cardHolderResult = $stmt->fetchObject(); 
                if($cardHolderResult == null) {
                    $cardHolderResult = array();
                    echo '{"authenticated": false, "error" : "Error: Invalid Card Number or PinCode"}'; 
                    return;
                } else {
                    if(!isset($_SESSION))
                    {
                        session_start();
                    } 
                    
                     $_SESSION['current_card_holder_id'] = $cardHolderResult->id;    
                 
                }
		$db = null;
                $cardHolderResult->authenticated = true;
		echo json_encode($cardHolderResult); 
                
                
                
	} catch(PDOException $e) {
		echo '{"error":{"text":'. $e->getMessage() .'}}'; 
	}
}


function logout() {
    session_destroy();
    echo '{"authenticated": false}'; 
    
}





?>